/* global Highcharts, d3, undersore, _, require, define */
/* jshint -W119 */

import {store} from "@/components/chart/common/store";

export const buildChart = function (myChart, data, columnFields, rowFields, options, echarts) {
  //地理维度
  const dimensionField = columnFields.concat(rowFields).find(function (d) {
    return d.geoMarker && d.geoMarker != '';
  });
  //度量
  const measureField = rowFields.concat(columnFields).find(function (d) {
    return d.slaveType === 1;
  });
  if (!dimensionField || !measureField) {
    return false;
  }
  let config = options.chartConfig;
  const geoMarker = dimensionField.geoMarker
  const city = dimensionField.city
  const province = dimensionField.province.id / 10000;
  let mapType = 'china';

  if (geoMarker == 'Geo-C-c') {
    if (dimensionField.city) {
      const geoJson = require('@/assets' + '/mapData/geometryCouties/' + city + '.json')
      echarts.registerMap(city, geoJson);
      mapType = city;
    } else {
      const geoJson = require('@/assets' + '/mapData/geometryProvince/' + province + '.json')
      echarts.registerMap(province, geoJson);
      mapType = province;
    }
  } else {
    const geoJson = require('@/assets' + '/mapData/china.json')
    echarts.registerMap('china', geoJson);
  }

  let cityList
  if (geoMarker == 'Geo-C' || geoMarker == 'Geo-C-c') {
    const geoCitySource = require('@/assets' + '/mapData/china-Lng-Lat.json')
    cityList = Array.prototype.concat.apply([], geoCitySource.Provinces.map(d => d.Citys));
  }

  const option = {
    tooltip: {
      trigger: 'item'
    },
    visualMap: {
      min: 0,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],           // 文本，默认为数值文本
      realtime: false,
      calculable: true,
      inRange: {
        color: config.MultiColors
      }
    },
    toolbox: {
      show: true,
      orient: 'vertical',
      left: 'right',
      top: 'center',
      feature: {
        mark: {show: true},
        dataView: {show: true, readOnly: false},
        restore: {show: true},
        saveAsImage: {show: true}
      }
    },
    series: [],
    others: {
      dimensionField: dimensionField,
      measureField: measureField,
      categories: {},
      data: data,
      labelFormater: config.labelFormater || "<%=name%>: <%=ratio%>",
      datamarking: options.dataMarking
    }
  };

  //数据条标签配置
  const labelOption = {
    show: config.textStyle["display"] !== "none",
    fontSize: config.textStyle["font-size"],
    fontFamily: config.textStyle["font-family"],
    color: config.textStyle["fill"],
    rotate: config.labelRotate,
    formatter: function (data) {
      if (!isNaN(data.value)) {
        return data.value;
      } else {
        return 0;
      }
    }
  }
  if (geoMarker == 'Geo-C') {
    const eff = {
      name: dimensionField.name,
      type: "effectScatter",
      coordinateSystem: "geo",
      symbolSize: function (val) {
        return Math.sqrt(Math.sqrt(val[2])) + 5
      },
      tooltip: {
        show: true,
        formatter: obj => obj.data.name + ':' + obj.data.value[2]
      },
      hoverAnimation: true,
      label: {
        show: false
      },
      itemStyle: {
        color: "#0efacc",
        shadowBlur: 2,
        shadowColor: "#333"
      },
      zlevel: 1
    }

    eff.data = data.map(d => {
      return {
        name: d[dimensionField.name],
        value: _.concat(getAreaCode(cityList, d[dimensionField.name]), d[measureField.name])
      }
    })

    option.geo = {
      map: mapType,
      roam: false,
      zoom: 1.2,
      selectedMode: false,
      itemStyle: {
        areaColor: config.GlobalColor,
        borderColor: config.borderColor,
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        shadowBlur: 5,
        borderWidth: 0.5,
        shadowColor: "rgba(0, 0, 0, 0.5)"
      }
    },
      option.series.push(eff)

  } else {
    const series = {
      name: measureField.name,
      type: 'map',
      map: mapType,
      tooltip: {},
      zoom: 1.2,
      selectedMode: false
    }
    series.label = labelOption
    series.itemStyle = {
      areaColor: config.GlobalColor,
      borderColor: store.darkMode ? '#fff' : '#000000',
      shadowOffsetX: 0,
      shadowOffsetY: 0,
      shadowBlur: 5,
      borderWidth: 0.5,
      shadowColor: "rgba(0, 0, 0, 0.5)"
    }
    series.data = data.map(function (d) {
      return {
        value: d[measureField.name],
        name: d[dimensionField.name]
      };
    });

    option.series.push(series);
  }


  const max = _.maxBy(data, d => d[measureField.name])
  option.visualMap.max = max[measureField.name]

  const min = _.minBy(data, d => d[measureField.name])
  option.visualMap.min = min[measureField.name]


  const chartInstance = new chart(myChart, option);
  return chartInstance;
};

const chart = function (myChart, opt) {
  let _mData = opt.series[0].data;

  let chart_opt = {};

  const setOption = function (opt, ext) {
    if (ext) {
      chart_opt = $.extend(true, chart_opt, opt);
    } else {
      chart_opt = opt;
    }

    myChart.setOption(chart_opt);
  };

  if (opt) {
    setOption(opt, true);
  }

  this.setOption = setOption;

  this.update = data => {
    _mData = data;
    chart_opt.series[0].data = data.map(function (d) {
      return {
        value: d[chart_opt.others.measureField.name],
        name: d[chart_opt.others.dimensionField.name]
      };
    });
    setOption(chart_opt, true);
  }

};

function getAreaCode(cityList, key) {
  const obj = cityList.find(item => item.Name == key)
  if (obj) {
    return [obj.Lng, obj.Lat]
  }
  return []
}


